package io.vertx.example.rxjava3.database.sqlclient;

import io.reactivex.rxjava3.core.Completable;
import io.vertx.jdbcclient.JDBCConnectOptions;
import io.vertx.launcher.application.VertxApplication;
import io.vertx.rxjava3.core.AbstractVerticle;
import io.vertx.rxjava3.jdbcclient.JDBCPool;
import io.vertx.rxjava3.sqlclient.*;
import io.vertx.sqlclient.PoolOptions;

import java.util.Arrays;

/*
 * @author <a href="mailto:emad.albloushi@gmail.com">Emad Alblueshi</a>
 */
public class Transaction extends AbstractVerticle {

  public static void main(String[] args) {
    VertxApplication.main(new String[]{Transaction.class.getName()});
  }

  @Override
  public Completable rxStart() {

    String sql = "CREATE TABLE colors (" +
      "id INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1, INCREMENT BY 1) PRIMARY KEY, " +
      "name VARCHAR(255), " +
      "datetime TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL)";

    Pool pool = JDBCPool.pool(vertx, new JDBCConnectOptions().setJdbcUrl("jdbc:hsqldb:mem:test?shutdown=true"), new PoolOptions());

    // Connect to the database
    return pool
      .rxWithTransaction(client -> client
      // Create table
      .query(sql).rxExecute()
      // Insert colors
      .flatMap(r -> client
        .preparedQuery("INSERT INTO colors (name) VALUES (?)")
        .rxExecuteBatch(Arrays.asList(Tuple.of("BLACK"), Tuple.of("PURPLE"))))
      // Get colors if all succeeded
      .flatMap(r -> client.query("SELECT * FROM colors").rxExecute())
      .toMaybe())// Subscribe to get the final result
      .doOnSuccess(rowSet -> {
        System.out.println("Results:");
        rowSet.forEach(row -> {
          System.out.println(row.toJson());
        });
      })
      .ignoreElement();
  }
}
